import Koa from "koa";
import logger from "koa-logger";
import onerror from "koa-onerror";
import { accessLogger, systemLogger } from "./logger/index.js";
import routers from "./router/index.js";
import bodyParser from "koa-bodyparser";
import serve from "koa-static";
import jwtAuth from "koa-jwt";
import { secret } from "./app.config.js";
import { deleteLogs } from "./utils/schedule.js";
// import startpuppeteer from './utils/puppeteer'

import path from "path"; //引入原生path模块
import { fileURLToPath } from "url";
const __filenameNew = fileURLToPath(import.meta.url);
const __dirnameNew = path.dirname(__filenameNew);

(async () => {
  const app = new Koa();
  //控制台打印
  app.use(logger());
  //错误处理中间件
  onerror(app);
  // 持久化日志
  app.use(accessLogger());
  // 静态资源托管
  app.use(serve(__dirnameNew + "/public"));

  // 删除日志
  deleteLogs(3);
  //开启爬虫
  // startpuppeteer()
  // 执行任务

  // 鉴权
  app.use(jwtAuth({ secret }).unless({ path: [/^\/api\/user\/login/] }));
  // 路由处理
  app.use(bodyParser());
  app.use(routers());
  // 报错监听
  app.on("error", (err) => {
    systemLogger.error(err);
  });

  app.listen(3000, () => console.log("KOA IS RUNNING !"));
})();
